package com.hotec.PROJECT_NAME.component.exception.handler;

import com.hotec.PROJECT_NAME.component.exception.exc.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 处理登录/权限等异常
 *
 * @author
 */
@RestController
@Slf4j
@SuppressWarnings("all")
public class ErrorServletHandler extends AbstractErrorController {
    private static final String ERROR_PATH = "/error";

    public ErrorServletHandler(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping(value = ERROR_PATH)
    public void handleError(HttpServletRequest request,HttpServletResponse response) {
        if(request.getAttribute("error")!=null){
            Object error = request.getAttribute("error");
            request.removeAttribute("error");
            throw new BizException(String.valueOf(error));
        }
        Map<String, Object> body = this.getErrorAttributes(request, ErrorAttributeOptions.defaults());
        String data = MapUtils.getString(body, "error", "system error") + ":" + MapUtils.getString(body, "message", "系统异常,请您稍后重试!");
        data = data.replaceAll("Authentication Failed: ", "").replaceAll("Internal Server Error:", "");
        String ex = MapUtils.getString(body, "exception");
        if ("com.hotec.yfcard.component.exception.exc.TokenException".equals(ex)) {
            response.setStatus(401);

           throw new BizException(901,data);
        }
            response.setStatus(200);
        throw new BizException(data);
    }


//    @Override
//    public String getErrorPath() {
//        return "/error";
//    }

}
